package com.leyou.sms.util;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.sms.config.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 封装短信工具类
 */

@Component
@Slf4j
public class SmsUtil {

    @Autowired
    private IAcsClient acsClient;
    @Autowired
    private SmsProperties prop;

    /**
     * 发送短信验证码
     */
    public void sendVerifyCode(String phone,String code){
        try {
            //格式化参数
            String param = String.format("{\"code\":\"%s\"}",code);
            sendMessage(phone,prop.getSignName(),prop.getVerifyCodeTemplate(),param);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 通用发送短信工具类
     * @param phone  电话
     * @param signName 短信签名
     * @param templateCode 模板
     * @param templateParam 模板参数
     */
    public void sendMessage(String phone,String signName,String templateCode,String templateParam){
        //准备发送短信的请求
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(prop.getDomain());
        request.setSysVersion(prop.getVersion());
        request.setSysAction(prop.getAction());
        request.putQueryParameter("RegionId", prop.getRegionID());
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", templateParam);

        try{
            CommonResponse response = acsClient.getCommonResponse(request);
            if (response.getHttpStatus() >= 300) {
                log.error("【SMS服务】发送短信失败。响应信息：{}", response.getData());
            }
            //解析结果
            Map<String, String> data = JsonUtils.toMap(response.getData(), String.class, String.class);
            //判断
            if (!"OK".equals(data.get("Code"))) {
                // 失败
                log.error("短信发送失败！原因：{}", data.get("Message"));
                throw new LyException(500, "短信发送失败！");
            }
            //发送成功
            log.info("【SMS服务】发送短信成功，手机号：{}, 响应：{}", phone, response.getData());
        }catch (ServerException e){
            log.error("【SMS服务】发送短信失败，服务端异常:", e);
        }catch (ClientException e){
            log.error("【SMS服务】发送短信失败，客户端异常:", e);
        }
    }
}
